Q-2: Rotate & Blink Animation OR Android Shared Preferences (5 Marks)
Questions​
a) Write a code to demonstrate the use of 'rotate' and 'blink' animation in android application. (5 marks)
OR
b) Write a note on android shared preferences. (5 marks)
Answers​
a) Rotate and Blink Animation Implementation​
Step 1: Create Animation XML Files​
res/anim/rotate_animation.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"
android:repeatMode="restart"
android:repeatCount="infinite" />
</set>
res/anim/blink_animation.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite" />
</set>
Step 2: Layout XML​
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<ImageView
android:id="@+id/rotateImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ic_star"
android:layout_marginBottom="32dp" />
<TextView
android:id="@+id/blinkText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blinking Text"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginBottom="32dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btnStartRotate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Rotate"
android:layout_marginEnd="16dp" />
<Button
android:id="@+id/btnStartBlink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Blink"
android:layout_marginEnd="16dp" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop All" />
</LinearLayout>
</LinearLayout>
Step 3: MainActivity Java Code​
public class MainActivity extends AppCompatActivity {
private ImageView rotateImage;
private TextView blinkText;
private Button btnStartRotate, btnStartBlink, btnStop;
private Animation rotateAnimation, blinkAnimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views
rotateImage = findViewById(R.id.rotateImage);
blinkText = findViewById(R.id.blinkText);
btnStartRotate = findViewById(R.id.btnStartRotate);
btnStartBlink = findViewById(R.id.btnStartBlink);
btnStop = findViewById(R.id.btnStop);
// Load animations
rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.rotate_animation);
blinkAnimation = AnimationUtils.loadAnimation(this, R.anim.blink_animation);
// Set click listeners
btnStartRotate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startRotateAnimation();
}
});
btnStartBlink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startBlinkAnimation();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopAllAnimations();
}
});
}
private void startRotateAnimation() {
if (rotateImage != null) {
rotateImage.startAnimation(rotateAnimation);
Toast.makeText(this, "Rotate animation started", Toast.LENGTH_SHORT).show();
}
}
private void startBlinkAnimation() {
if (blinkText != null) {
blinkText.startAnimation(blinkAnimation);
Toast.makeText(this, "Blink animation started", Toast.LENGTH_SHORT).show();
}
}
private void stopAllAnimations() {
if (rotateImage != null) {
rotateImage.clearAnimation();
}
if (blinkText != null) {
blinkText.clearAnimation();
}
Toast.makeText(this, "All animations stopped", Toast.LENGTH_SHORT).show();
}
}
Alternative: Programmatic Animation Creation​
// Create rotate animation programmatically
private Animation createRotateAnimation() {
RotateAnimation rotate = new RotateAnimation(
0f, 360f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
);
rotate.setDuration(2000);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
return rotate;
}
// Create blink animation programmatically
private Animation createBlinkAnimation() {
AlphaAnimation blink = new AlphaAnimation(1.0f, 0.0f);
blink.setDuration(600);
blink.setRepeatMode(Animation.REVERSE);
blink.setRepeatCount(Animation.INFINITE);
return blink;
}
b) Android Shared Preferences​
Definition​
SharedPreferences is a lightweight storage mechanism in Android used to store small amounts of primitive data (key-value pairs) persistently across app sessions.
Key Characteristics​
- Persistent Storage: Data survives app restarts and device reboots
- Key-Value Storage: Stores data as key-value pairs
- Primitive Data Types: Supports boolean, int, long, float, String
- XML Storage: Data stored in XML files in app's private directory
- Thread-Safe: Safe for concurrent access
Creating and Accessing SharedPreferences​
1. Get SharedPreferences Instance:
// Private to app
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Activity-specific
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
// Default shared preferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
2. Writing Data:
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
// Store different data types
editor.putString("username", "john_doe");
editor.putInt("user_age", 25);
editor.putBoolean("is_logged_in", true);
editor.putFloat("app_version", 1.5f);
editor.putLong("last_login", System.currentTimeMillis());
// Commit changes
editor.apply(); // Asynchronous
// or
editor.commit(); // Synchronous
3. Reading Data:
SharedPreferences sharedPref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Read with default values
String username = sharedPref.getString("username", "default_user");
int age = sharedPref.getInt("user_age", 0);
boolean isLoggedIn = sharedPref.getBoolean("is_logged_in", false);
float version = sharedPref.getFloat("app_version", 1.0f);
long lastLogin = sharedPref.getLong("last_login", 0);
Complete Example: User Preferences​
public class UserPreferences {
private static final String PREF_NAME = "UserPrefs";
private static final String KEY_USERNAME = "username";
private static final String KEY_EMAIL = "email";
private static final String KEY_IS_FIRST_TIME = "is_first_time";
private static final String KEY_THEME = "theme";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private Context context;
public UserPreferences(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
// Save user data
public void saveUserData(String username, String email) {
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_EMAIL, email);
editor.apply();
}
// Get username
public String getUsername() {
return sharedPreferences.getString(KEY_USERNAME, "");
}
// Get email
public String getEmail() {
return sharedPreferences.getString(KEY_EMAIL, "");
}
// Set first time user flag
public void setFirstTimeUser(boolean isFirstTime) {
editor.putBoolean(KEY_IS_FIRST_TIME, isFirstTime);
editor.apply();
}
// Check if first time user
public boolean isFirstTimeUser() {
return sharedPreferences.getBoolean(KEY_IS_FIRST_TIME, true);
}
// Save theme preference
public void saveTheme(String theme) {
editor.putString(KEY_THEME, theme);
editor.apply();
}
// Get theme
public String getTheme() {
return sharedPreferences.getString(KEY_THEME, "light");
}
// Clear all preferences
public void clearPreferences() {
editor.clear();
editor.apply();
}
// Remove specific key
public void removeKey(String key) {
editor.remove(key);
editor.apply();
}
}
Usage in Activity​
public class MainActivity extends AppCompatActivity {
private UserPreferences userPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userPrefs = new UserPreferences(this);
// Check if first time user
if (userPrefs.isFirstTimeUser()) {
// Show welcome screen
showWelcomeScreen();
userPrefs.setFirstTimeUser(false);
}
// Load user data
String username = userPrefs.getUsername();
String email = userPrefs.getEmail();
if (!username.isEmpty()) {
// User is logged in
loadUserProfile(username, email);
}
}
private void saveUserLogin(String username, String email) {
userPrefs.saveUserData(username, email);
}
private void logout() {
userPrefs.clearPreferences();
// Redirect to login screen
}
}
Best Practices​
- Data Types: Only store primitive data types
- Size Limitation: Don't store large amounts of data
- Security: Don't store sensitive data (passwords, tokens)
- apply() vs commit(): Use apply() for better performance
- Key Management: Use constants for keys to avoid typos
- Backup: Data is not backed up by default
Common Use Cases​
- User preferences and settings
- App configuration
- Login state
- Theme preferences
- First-time user flags
- Simple caching of small data